using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web.UI.HtmlControls;
using ALib;
using ALib.Data.CSVOperation;
using ALib.Data.IO;
//using ALib.Net;
using TradingPlatform.IB.Operations;

namespace TradingPlatform.IB.Utility
{
    class TradingKernel_SaveAccountUpdate : TradingKernel
    {
        private InteractiverBrokers _interactiverBrokers;

        public TradingKernel_SaveAccountUpdate()
            : base("InteractiveBrokers_SaveAccountUpdate")
        {
        }

        public TradingKernel_SaveAccountUpdate(bool sendEmail)
            : this()
        {
            if (sendEmail)
            {
                ConnectTradingApi();
                StartTimerBasedTrading();   
            }
        }

        public override void ConnectTradingApi()
        {
            _interactiverBrokers = new InteractiverBrokers(TradingComm);
            string connectReply = _interactiverBrokers.Connect();
            DisplayStatus(connectReply);
        }

        protected override void InitToStart()
        {
            const string accountCode = @"";
            _interactiverBrokers.AccountUpdates.RequestAccountUpdates(accountCode);
        }

        protected override void Timer0_Process()
        {
            _timer0.Stop();

            string savePath = string.Format(@"Log\AccountUpdate\{0}", DateTime.Now.ToString(DateTimeFormatType.Simple));
            
            SaveNewAccountUpdate(savePath);
            DisplayStatus(string.Format(@"Saved to [{0}]", savePath));
            SendEmail(savePath);
        }

        protected override void Timer1_Process()
        {
            // Display error messages.
            foreach (string errorMessage in _interactiverBrokers.ErrorMessageList)
            {
                DisplayErrorMessage(errorMessage);
            }
            _interactiverBrokers.ErrorMessageList.Clear();
        }

        protected override void Timer2_Process()
        {
            //throw new System.NotImplementedException();
        }

        protected override void Timer3_Process()
        {
            //throw new System.NotImplementedException();
        }

        protected override void RequestMarketData()
        {
            throw new System.NotImplementedException();
        }

        protected override void SendOrders(List<string> orders)
        {
            throw new System.NotImplementedException();
        }

        public override void Dispose()
        {
            if (_interactiverBrokers != null)
            {
                _interactiverBrokers.Disconnect();
                _interactiverBrokers.Dispose();
            }
        }

        protected override SortedList<string, string> GetStrategyTickerNameList(List<string> tickerNameList)
        {
            throw new System.NotImplementedException();
        }

        private void SaveNewAccountUpdate(string savePath)
        {
            List<string> accountUpdateInfoList = _interactiverBrokers.AccountUpdates._result;

            FilesIO.ToOneFile(accountUpdateInfoList, new FileInfo(savePath + @"\AccountUpdate.csv"));
        }

        private void SendEmail(string savePath)
        {
            FileInfo accountUpdateFile = new FileInfo(string.Format(@"{0}\{1}", savePath, @"AccountUpdate.csv"));

            List<string[]> accountUpdateRecords = CSVEditor.Open(accountUpdateFile.FullName);

            List<string> emailBodyRecords = new List<string>();
            emailBodyRecords.Add(@"TickerName, OpenPosition, P&L in XXX, P&L in USD");
            double totalPnl = 0;

            for (int i = 1; i < accountUpdateRecords.Count; i++)
            {
                string[] accountUpdateRecord = accountUpdateRecords[i];
                string exchange = accountUpdateRecord[(int)AccountUpdateItemType.primaryExchange];
                string secType = accountUpdateRecord[(int)AccountUpdateItemType.secType];
                string symbol = accountUpdateRecord[(int)AccountUpdateItemType.symbol];
                string expiry = accountUpdateRecord[(int)AccountUpdateItemType.expiry];
                expiry = expiry.Length == 8 ? expiry.Substring(0, 6) : expiry;
                string currency = accountUpdateRecord[(int)AccountUpdateItemType.currency];
                string openPosition = accountUpdateRecord[(int)AccountUpdateItemType.position];
                double pnl = double.Parse(accountUpdateRecord[(int)AccountUpdateItemType.realizedPNL]) + double.Parse(accountUpdateRecord[(int)AccountUpdateItemType.unrealizedPNL]);

                string tickerName = TickerNameAndId.ToTickerName(exchange, secType, symbol, expiry, currency);

                if (_tickerInfoDb.SymbolList.Contains(symbol))
                {
                    double exchangeRateXxxUsd = _tickerInfoDb.ExchangeRate.GetExchangeRateXxxUsd(currency);
                    double pnlUsd = pnl * exchangeRateXxxUsd;
                    totalPnl += pnlUsd;
                    string outputString = string.Format(@"{0},{1},{2},{4}", tickerName, openPosition, pnl, currency, pnlUsd);
                    emailBodyRecords.Add(outputString);
                }
            }

            emailBodyRecords.Add(@",,,");
            emailBodyRecords.Add(string.Format(@"Total,,,{0}", totalPnl));

            if (emailBodyRecords.Count>3)
            {
                TradingHtmlTable tradingHtmlTable = new TradingHtmlTable();
                foreach (string emailBodyRecord in emailBodyRecords)
                {
                    tradingHtmlTable.AddRow(emailBodyRecord.Split(new char[] { ',' }));
                }

                List<string[]> emailRecords = CSVEditor.Open(@"Configuration\TradingPlatformEmailList.csv", "//");
                foreach (string[] emailRecord in emailRecords)
                {
                    string toEmailAddress = emailRecord[0];
                    string toName = emailRecord[1];
                    /*EMail.SendEmail_Gmail("alpha.trading.system.public@gmail.com", "AlphaTradingSystemPublic",
                                          toEmailAddress, toName,
                                          "alpha.trading.system.public", "xxxx",
                                          tradingHtmlTable.ToString(), true,
                                          string.Format(@"Asia Pacific P&L [{0}].", DateTime.Now.ToString(DateTimeFormatType.DateSimple)),
                                          accountUpdateFile.FullName);
                     * */
                }
            }
        }
    }
}
